#!/usr/bin/env node

// 全系统自动化测试运行脚本
const { execSync } = require('child_process')
const fs = require('fs')
const path = require('path')

// 配置
const config = {
  baseUrl: 'http://127.0.0.1:8080',
  testResultsDir: 'cypress/results',
  screenshotsDir: 'cypress/screenshots',
  videosDir: 'cypress/videos',
  maxRetries: 3,
  timeout: 300000, // 5分钟
}

// 颜色输出
const colors = {
  reset: '\x1b[0m',
  bright: '\x1b[1m',
  dim: '\x1b[2m',
  red: '\x1b[31m',
  green: '\x1b[32m',
  yellow: '\x1b[33m',
  blue: '\x1b[34m',
  magenta: '\x1b[35m',
  cyan: '\x1b[36m',
}

// 工具函数
function log(message, color = colors.reset) {
  console.log(`${color}${message}${colors.reset}`)
}

function createDir(dirPath) {
  if (!fs.existsSync(dirPath)) {
    fs.mkdirSync(dirPath, { recursive: true })
  }
}

function checkServer() {
  return new Promise(resolve => {
    const http = require('http')
    const options = new URL(config.baseUrl)

    const req = http.request(
      {
        hostname: options.hostname,
        port: options.port,
        path: '/',
        method: 'GET',
        timeout: 5000,
      },
      res => {
        resolve(res.statusCode === 200)
      }
    )

    req.on('error', () => resolve(false))
    req.on('timeout', () => resolve(false))
    req.end()
  })
}

async function waitForServer(maxAttempts = 30) {
  log('检查服务器状态...', colors.yellow)

  for (let i = 0; i < maxAttempts; i++) {
    const isReady = await checkServer()
    if (isReady) {
      log('✅ 服务器已就绪', colors.green)
      return true
    }

    process.stdout.write('.')
    await new Promise(resolve => setTimeout(resolve, 1000))
  }

  log('\n❌ 服务器未就绪，请确保前端开发服务器已启动', colors.red)
  return false
}

function runCypressTest(specPattern = 'cypress/e2e/**/*.cy.ts') {
  try {
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    const resultsDir = path.join(config.testResultsDir, timestamp)

    createDir(resultsDir)

    const command = [
      'npx cypress run',
      `--spec "${specPattern}"`,
      `--config baseUrl=${config.baseUrl}`,
      '--browser chrome',
      '--headed', // 显示浏览器界面
      '--no-exit', // 保持浏览器打开
      `--reporter mochawesome`,
      `--reporter-options "reportDir=${resultsDir},overwrite=false,html=true,json=true"`,
    ].join(' ')

    log(`运行测试: ${command}`, colors.cyan)

    const output = execSync(command, {
      stdio: 'inherit',
      timeout: config.timeout,
      encoding: 'utf8',
    })

    return { success: true, output }
  } catch (error) {
    return { success: false, error: error.message }
  }
}

function generateTestReport(results) {
  const report = {
    timestamp: new Date().toISOString(),
    config,
    results,
    summary: {
      total: results.length,
      passed: results.filter(r => r.success).length,
      failed: results.filter(r => !r.success).length,
    },
  }

  const reportPath = path.join(config.testResultsDir, 'test-report.json')
  fs.writeFileSync(reportPath, JSON.stringify(report, null, 2))

  return reportPath
}

// 主函数
async function main() {
  log('🚀 启动全系统自动化测试', colors.magenta)
  log('='.repeat(50), colors.dim)

  try {
    // 1. 检查服务器
    const serverReady = await waitForServer()
    if (!serverReady) {
      process.exit(1)
    }

    // 2. 创建必要的目录
    createDir(config.testResultsDir)
    createDir(config.screenshotsDir)
    createDir(config.videosDir)

    // 3. 运行不同类型的测试
    const testSuites = [
      { name: '认证测试', pattern: 'cypress/e2e/auth.cy.ts' },
      { name: '案件测试', pattern: 'cypress/e2e/lawcase.cy.ts' },
      { name: '全系统测试', pattern: 'cypress/e2e/full-system-test.cy.ts' },
    ]

    const results = []

    for (const suite of testSuites) {
      log(`\n📋 运行 ${suite.name}...`, colors.blue)

      const result = runCypressTest(suite.pattern)
      results.push({
        name: suite.name,
        pattern: suite.pattern,
        ...result,
      })

      if (result.success) {
        log(`✅ ${suite.name} 完成`, colors.green)
      } else {
        log(`❌ ${suite.name} 失败`, colors.red)
      }
    }

    // 4. 生成报告
    const reportPath = generateTestReport(results)
    log(`\n📊 测试报告已生成: ${reportPath}`, colors.cyan)

    // 5. 显示总结
    log('\n' + '='.repeat(50), colors.dim)
    log('📈 测试总结:', colors.magenta)
    log(`总测试套件: ${results.length}`, colors.blue)
    log(`通过: ${results.filter(r => r.success).length}`, colors.green)
    log(`失败: ${results.filter(r => !r.success).length}`, colors.red)
  } catch (error) {
    log(`❌ 测试运行失败: ${error.message}`, colors.red)
    process.exit(1)
  }
}

// 运行
if (require.main === module) {
  main().catch(console.error)
}

module.exports = { main, runCypressTest, waitForServer }
